<?php

namespace App\Http\Controllers\Admin;

use App\Models\AnswerActivity;
use App\Models\AnswerActivityGift;
use App\Models\AnswerActivityGiftConfig;
use App\Validate\AnswerActivityGiftValidate;
use Illuminate\Support\Facades\DB;

/**
 * 活动礼物管理
 */
class AnswerActivityGiftController extends CommonController
{

    public $model = null;
    public $validate = null;

    public function __construct()
    {
        parent::__construct();

        $this->model = new AnswerActivityGift();
        $this->validate = new AnswerActivityGiftValidate();
    }

    /**
     * 列表
     * @param act_id int 活动id
     * @param unit_id int 区域id
     * @param type int 0或空表示  1文化红包 2精美礼品
     * @param way int 0或空表示  领取方式   1 自提  2邮递   红包无此选项
     * @param page int 当前页
     * @param limit int 分页大小
     * @param start_time datetime 创建时间范围搜索(开始) 
     * @param end_time datetime 创建时间范围搜索(结束) 
     * @param keywords string 搜索关键词(类型名称)
     */
    public function lists()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('list')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        //判断是否可以添加礼物
        $isAllowAddGift = $this->model->isAllowAddGift($this->request->act_id);
        if ($isAllowAddGift !== true) {
            return $this->returnApi(202, $isAllowAddGift);
        }

        $page = $this->request->page ? intval($this->request->page) : 1;
        $limit = $this->request->limit ? intval($this->request->limit) : 10;
        $start_time = $this->request->start_time;
        $end_time = $this->request->end_time;
        $type = $this->request->type;
        $way = $this->request->way;
        $keywords = $this->request->keywords;
        $act_id = $this->request->act_id;
        $unit_id = $this->request->unit_id;


        $res = $this->model->lists(null, $act_id, $keywords, $unit_id, $type, $way, $start_time, $end_time, $page, $limit);

        if ($res['total'] == 0 || !$res['data']) {
            return $this->returnApi(203, "暂无数据");
        }

        $res = $this->disPageData($res);
        foreach ($res['data'] as $key => $val) {
            $res['data'][$key]['intro'] = strip_tags($val['intro']);

            $res['data'][$key]['img'] = $val['type'] == 1 ? 'default/default_red_img.jpg' : $val['img'];

            $res['data'][$key]['unit_name'] = !empty($val['con_unit']['name']) ?  $val['con_unit']['name'] : config('other.unit_name');
            $res['data'][$key][$this->list_index_key] = $this->addSerialNumberOne($key, $page, $limit);

            unset($res['data'][$key]['con_unit']);
        }

        return $this->returnApi(200, "查询成功", true, $res);
    }

    /**
     * 详情
     * @param id int 类型id
     */
    public function detail()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('detail')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $res = $this->model->detail($this->request->id);

        if (!$res) {
            return $this->returnApi(201, "参数传递错误");
        }

        return $this->returnApi(200, "获取成功", true, $res->toArray());
    }

    /**
     * 新增
     * @param act_id int活动id
     * @param unit_id int单位id 选了代表是单位专属，不选代表为公共
     * @param name string 名称   最多 30个字符
     * @param img string 图片
     * @param percent string 中奖概率 保留2位小数  例：中奖概率为  95%  则参数为  95.00 
     * @param price string 红包金额 
     * @param total_number string 礼物总数量
     * @param type tinyint 1文化红包 2精美礼品
     * @param way tinyint 领取方式   1 自提  2邮递   红包无此选项
     * @param start_time datetime 自提开始时间
     * @param end_time datetime 自提结束时间
     * @param tel string 联系电话
     * @param contacts string 联系人
     * @param province string 省
     * @param city string 市
     * @param district string 区
     * @param address string 详细地址
     * @param remark string 自提备注
     * @param intro string 礼品备注
     */
    public function add()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('add')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $activityGiftConfigModel = new AnswerActivityGiftConfig();
        $percent_way = $activityGiftConfigModel->where('act_id' , $this->request->act_id)->value('percent_way');
          //判断总概率，不能超过100
          if($percent_way == 2){
            $total_percent = $activityGiftConfigModel->getActTotalPercent($this->request->act_id);
            if($total_percent + $this->request->percent > 100){
                 return $this->returnApi(201, '活动总概率超过100%，不能设置为所有奖品总概率方式，若要设置，请先修改奖品概率');
            }
         }

        //判断礼物类型
        if (!in_array($this->request->type, config('other.answer_activity_gift_type'))) {
            return $this->returnApi(201, '礼物类型错误');
        }

        if($this->request->type == 1 && (empty($this->request->price) || $this->request->price < 0.3 || $this->request->price > 500)){
            return $this->returnApi(202, '红包金额必须在 0.3~500 之间');
        }


        //判断是否可以添加礼物
        $isAllowAddGift = $this->model->isAllowAddGift($this->request->act_id);
        if ($isAllowAddGift !== true) {
            return $this->returnApi(202, $isAllowAddGift);
        }

        //是否允许选单位id
        $node = AnswerActivity::where('id', $this->request->act_id)->value('node');
        if ($node == 1 && !empty($this->request->unit_id)) {
            return $this->returnApi(202, '此活动为独立活动，不能选择单位');
        }
        //判断如果是自提礼物，自提点不能为空
        $pickInfoIsFull = $this->model->pickInfoIsFull($this->request->all());
        if ($pickInfoIsFull !== true) {
            return $this->returnApi(202, $pickInfoIsFull);
        }

        // $condition[] = ['act_id', '=', $this->request->act_id];

        // $is_exists = $this->model->nameIsExists($this->request->name, 'name', null, 1, $condition);
        // if ($is_exists) {
        //     return $this->returnApi(202, "此名称已存在");
        // }
        $this->request->merge(['unit_id'=>$this->request->unit_id ? $this->request->unit_id : 0]);
        $res = $this->model->add($this->request->all());

        if (!$res) {
            return $this->returnApi(202, "新增失败");
        }
        return $this->returnApi(200, "新增成功", true);
    }

    /**
     * 修改
     * @param id int 礼物id
     * @param unit_id int单位id 选了代表是单位专属，不选代表为公共
     * @param name string 名称   最多 30个字符
     * @param img string 图片
     * @param percent string 中奖概率  保留2位小数  例：中奖概率为  95%  则参数为  95.00 
     * @param price string 红包金额 
     * @param total_number string 礼物总数量
     * @param type tinyint 1文化红包 2精美礼品
     * @param way tinyint 领取方式   1 自提  2邮递   红包无此选项
     * @param start_time datetime 自提开始时间
     * @param end_time datetime 自提结束时间
     * @param tel string 联系电话
     * @param contacts string 联系人
     * @param province string 省
     * @param city string 市
     * @param district string 区
     * @param address string 详细地址
     * @param remark string 自提备注
     * @param intro string 礼品备注
     */
    public function change()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('change')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }


        //判断礼物类型
        if (!in_array($this->request->type, config('other.answer_activity_gift_type'))) {
            return $this->returnApi(201, '礼物类型错误');
        }

        if($this->request->type == 1 && (empty($this->request->price) || $this->request->price < 0.3 || $this->request->price > 500)){
            return $this->returnApi(202, '红包金额必须在 0.3~500 之间');
        }

        $result = $this->model->find($this->request->id);
        if (empty($result)) {
            return $this->returnApi(202, '参数传递错误');
        }
        if ($result->use_number > $this->request->total_number) {
            return $this->returnApi(202, '礼物总数量不能小于用户已获得奖品数量');
        }

        $activityGiftConfigModel = new AnswerActivityGiftConfig();
        $percent_way = $activityGiftConfigModel->where('act_id' , $result->id)->value('percent_way');
          //判断总概率，不能超过100
          if($percent_way == 2){
            $total_percent = $activityGiftConfigModel->getActTotalPercent($result->id);
            if($total_percent + $this->request->percent > 100){
                 return $this->returnApi(201, '活动总概率超过100%，不能设置为所有奖品总概率方式，若要设置，请先修改奖品概率');
            }
         }


        //判断是否可以添加礼物
        $isAllowAddGift = $this->model->isAllowAddGift($result->act_id);
        if ($isAllowAddGift !== true) {
            return $this->returnApi(202, $isAllowAddGift);
        }

        //是否允许选单位id
        $node = AnswerActivity::where('id', $result->act_id)->value('node');
        if ($node == 1 && !empty($this->request->unit_id)) {
            return $this->returnApi(202, '此活动为独立活动，不能选择单位');
        }
        //判断如果是自提礼物，自提点不能为空
        $pickInfoIsFull = $this->model->pickInfoIsFull($this->request->all());
        if ($pickInfoIsFull !== true) {
            return $this->returnApi(202, $pickInfoIsFull);
        }

        // $condition[] = ['act_id', '=', $this->request->act_id];

        // $is_exists = $this->model->nameIsExists($this->request->name, 'name', null, 1, $condition);
        // if ($is_exists) {
        //     return $this->returnApi(202, "此名称已存在");
        // }
        $this->request->merge(['unit_id'=>$this->request->unit_id ? $this->request->unit_id : 0]);
        $res = $this->model->change($this->request->all());

        if (!$res) {
            return $this->returnApi(202, "修改失败");
        }
        return $this->returnApi(200, "修改成功", true);
    }

    /**
     * 删除
     * @param id int 类型id
     */
    public function del()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('del')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $result = $this->model->find($this->request->id);
        if (empty($result)) {
            return $this->returnApi(202, '参数传递错误');
        }
        if (!empty($result->use_number)) {
            return $this->returnApi(202, '此礼物已有用户获取，不允许删除');
        }

        $res = $this->model->del($this->request->id);

        if ($res === true) {
            return $this->returnApi(200, "删除成功", true);
        }
        return $this->returnApi(202, $res);
    }
}
